package com.minelx.datamicroscope.core.query;

import com.minelx.datamicroscope.core.condition.KeyOperandCondition;
import com.minelx.datamicroscope.core.values.CommonField;
import com.minelx.sqlstructures.statements.SelectBuilder;
import com.minelx.sqlstructures.statements.clause.Sql;
import com.minelx.statementsplus.cha.base.TaskCommitment;

import static com.minelx.datamicroscope.core.condition.Operand.gt;
import static java.lang.String.format;

class EnrichedTaskCommitment {

	private final SelectBuilder builder;

	private final CommonField primaryField;

	private final String databaseIndex;

	EnrichedTaskCommitment(CommonField primaryField, String databaseIndex, SelectBuilder builder) {
		this.primaryField = primaryField;
		this.databaseIndex = databaseIndex;
		this.builder = builder;
	}

	String toSQLText() {
		return databaseIndex + "=> " + builder.build().toText();
	}

	TaskCommitment commonTaskCommitment() {
		return new TaskCommitment(primaryField.name(), toSQLText(), "", "", "");
	}

	TaskCommitment wrappedWithSelectBlock(TaskCommitment commonTaskCommitment) {
		// wrap with SELECT * block
		SelectBuilder body = builder.copy();

		body.where().remove(KeyOperandCondition.of(primaryField, gt("{{BVAL}}")).sqlText());

		body.orderBy(Sql.empty());
		body.limit(Sql.empty());

		String innerSql = body.build().toText();

		return new TaskCommitment(commonTaskCommitment.loopId(),
				format("%s=> " +
								"SELECT * FROM (%s) a " +
								"WHERE a.%s > {{BVAL}} " +
								"ORDER BY a.%s LIMIT 1000;",
						databaseIndex,
						innerSql.substring(0, innerSql.length() - 1),
						primaryField.name(),
						commonTaskCommitment.loopId()),
				commonTaskCommitment.childSql(),
				commonTaskCommitment.additionalValues(),
				commonTaskCommitment.multipleValues());
	}
}
